package com.example.printservice.initiate;


import com.example.printservice.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

@Component
@Slf4j
public class Initiate implements ApplicationRunner, ClearDir {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 创建存储用户上传以及处理结果的文件目录
        Path path = Paths.get(Constants.RESULT_PATH);
        try {
            Path pathCreate = Files.createDirectories(path);
            log.info(pathCreate.toString() + "已创建！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 多线程定时清理文件夹
    @Override
    @Scheduled(cron = "0 0 1 * * ?")
    @Async
    public void clearDir() {
        Path path = Paths.get(Constants.FILE_PATH);
        try {
            Files.walkFileTree(path,
                    new SimpleFileVisitor<Path>() {
                        // 先去遍历删除文件
                        @Override
                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                            Files.delete(file);
                            log.info("文件夹被删除:" + file);
                            return FileVisitResult.CONTINUE;
                        }

                        // 再去遍历删除目录
                        @Override
                        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                            Files.delete(dir);
                            log.info("文件夹被删除:" + dir);
                            return FileVisitResult.CONTINUE;
                        }

                    }
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
